package org.ielts.action;

import static com.yifeng.struts2.ResultConstants.*;
import static com.yifeng.struts2.ResultParameters.*;
import static com.yifeng.struts2.ActionUtils.*;
import static com.yifeng.struts2.RequestParameters.*;

import org.apache.commons.lang.StringUtils;
import org.ielts.course.CourseInfoTest;
import org.ielts.domain.course.BillingModel;
import org.ielts.domain.course.Content;
import org.ielts.domain.course.Form;
import org.ielts.domain.course.Subject;
import org.ielts.domain.query.SubjectQuery;
import org.ielts.service.ContentService;
import org.ielts.service.SubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.yifeng.modules.annotations.Operation;
import com.yifeng.web.Paginations;

public class SubjectAction extends BaseAction {

	@Autowired
	SubjectService subjectService;

	@Autowired
	ContentService contentService;

	@Operation(result = FILL)
	public String modifySubject() {
		Form[] forms = Form.values();
		put("forms", forms);

		BillingModel[] billingModels = BillingModel.values();
		put("billingModels", billingModels);

		String id = form.readString("id");

		Subject subject = subjectService.find(id);
		put("subject", subject);

		Iterable<Content> contents = contentService.listAllContent();
		put("contents", contents);
		return FILL;
	}

	@Autowired
	SubjectQuery subjectQuery;

	@Operation(result = FILL)
	public String listSubject() {
		Pageable pageable = getPageable(30);

		buildSubjectQuery();

		Page<Subject> subjects = subjectService.listSubject(subjectQuery, pageable);

		put("subjects", subjects);
		put(PAGINATIONS, new Paginations(subjects));

		Iterable<Content> contents = contentService.listAllContent();
		put("contents", contents);
		return FILL;
	}

	private void buildSubjectQuery() {
		String form = super.form.readString("form");
		if (StringUtils.isNotBlank(form)) {
			try {
				Form formEnum = Form.valueOf(form);
				subjectQuery.setForm(formEnum);
			} catch (Exception ex) {

			}
		}

		String bill = super.form.readString("model");
		if (StringUtils.isNotBlank(bill)) {
			try {
				BillingModel billingModel = BillingModel.valueOf(bill);
				subjectQuery.setBillingModel(billingModel);
			} catch (Exception ex) {

			}
		}

		String[] contents = super.form.readStrings("content");
		if (contents.length > 0) {
			subjectQuery.setContents(contents);
		}
	}
}
